package com.blockmeta.bbs.immodule.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.umeng.ShareResTask;
import com.blockmeta.bbs.businesslibrary.umeng.TypeDescribe;
import com.blockmeta.bbs.businesslibrary.umeng.circle.IShareObject;
import com.blockmeta.bbs.businesslibrary.umeng.circle.ShareContent;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.IMCircleShareAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.bean.databean.ShareBean;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.pojo.IMCircleEntityBook;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.subscribers.ResourceSubscriber;

/**
 * IM 圈子分享 选择圈子并分享页面
 */
@Route(path = RouterPath.IM_SHARE_ACTIVITY,extras = RouterConstant.EXTRAL_LOGIN)
public class IMShareActivity extends BaseActivity {
    @BindView(R2.id.rcv_circle_list)
    RecyclerView mRcvCircleList;

    IMCircleShareAdapter mCircleShareAdapter;

    @Autowired(name = Constant.ZERO)
    ShareContent mShareContent;

    private List<ICircleEntry> mICircleEntries = new ArrayList<>();

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_imshare, null);
    }


    @OnClick({R2.id.fl_back, R2.id.fl_next})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();
        } else if (i == R.id.fl_next) {
            doShare();
        }
    }

    /**
     * 开始分享
     */
    private void doShare() {
        final ICircleEntry selected = mCircleShareAdapter.getCheckedItems();
        if (selected == null){
            ToastUtil.show("请选择一个圈子分享");
            return;
        }
        ShareResTask.doTask(new ShareResTask.Task<Boolean>() {
            @Override
            public Boolean doInBackground() {
                if (mShareContent.mShareType == IShareObject.ShareType.WEB_PAGE){
                    ShareBean contentBean = new ShareBean();
                    contentBean.setId(mShareContent.id);
                    contentBean.setImg(mShareContent.mThumb);
                    contentBean.setName(mShareContent.mTitle);
                    contentBean.setDesc(mShareContent.mDescribe);
                    contentBean.setUrl(mShareContent.mUrl);

                    sendWebShareToChat(selected,contentBean);
                }else if (mShareContent.mShareType == IShareObject.ShareType.CUSTOM){
                    sendCustomShareToChat(selected);
                }else {
                    sendImageShareToChat(selected);
                }
                return true;
            }

            @Override
            public void doOnUIThread(Boolean aBoolean) {
                try {
                    ARouter.getInstance().build(RouterPath.IM_UCGChatActivity_ACTIVITY)
                            .withString(Constant.ZERO,String.valueOf(selected.getId()))
                            .navigation(mContext, mNavCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    NavCallback mNavCallback = new NavCallback() {
        @Override
        public void onArrival(Postcard postcard) {
            finish();
        }
    };

    /**
     * 分享自定义类型消息 如K线 F10
     * @param entry 分享目标的基本信息
     */
    private void sendCustomShareToChat(ICircleEntry entry) {
        IMApplicationContext.getIMMetaService().sendCustomMessage(ChatMessage.MSG_TYPE_UCG, entry.getId(), mShareContent.mCustomShareJson, ChatMessage.CUSTOM_TYPE_KLINE,null);
    }
    /**
     * 分享图片
     * @param entry 分享目标的基本信息
     */
    private void sendImageShareToChat(ICircleEntry entry) {
        IMApplicationContext.getIMMetaService().sendImageMessage(ChatMessage.MSG_TYPE_UCG,entry.getId(),mShareContent.mBitmap);
    }

    /**
     *  分享网页
     * @param entry 分享目标的基本信息
     */
    private void sendWebShareToChat(ICircleEntry entry, ShareBean contentBean) {
        int typeDesc;
        if (mShareContent.mTypeDescribe == TypeDescribe.BBS) {
            typeDesc = ChatMessage.CUSTOM_TYPE_FORUMPOST;

        } else if (mShareContent.mTypeDescribe == TypeDescribe.NEWS) {
            typeDesc = ChatMessage.CUSTOM_TYPE_POST;

        } else if (mShareContent.mTypeDescribe == TypeDescribe.ACTIVITY) {
            typeDesc = ChatMessage.CUSTOM_TYPE_ACTIVITY;

        } else if (mShareContent.mTypeDescribe == TypeDescribe.CHAIN_CRAFT) {
            typeDesc = ChatMessage.CUSTOM_TYPE_GOODHING;

        } else if (mShareContent.mTypeDescribe == TypeDescribe.USER_CARD){
            contentBean.setCard_type(Params.USER_PERSON);
            typeDesc = ChatMessage.CUSTOM_TYPE_CARD;
        }else if (mShareContent.mTypeDescribe == TypeDescribe.CIRCLE_CARD){
            contentBean.setCard_type(Params.USER_GROUP);
            typeDesc = ChatMessage.CUSTOM_TYPE_CARD;
        }else {
            typeDesc = ChatMessage.CUSTOM_TYPE_POST;

        }
        IMApplicationContext.getIMMetaService().sendCustomMessage(ChatMessage.MSG_TYPE_UCG, entry.getId(), contentBean.toJsonString(), typeDesc,null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mRcvCircleList.setLayoutManager(new LinearLayoutManager(mContext));
        mCircleShareAdapter = new IMCircleShareAdapter(R.layout.item_im_circle_share,mICircleEntries);
        mRcvCircleList.setAdapter(mCircleShareAdapter);
        netWork();
    }

    //由上层页面收到事件后调用设置数据！
    public void netWork() {
        ProgressBarUtil.showProgress(mContext);
        //从数据库中获取已加入的群组
        final List<IMUserEntity> circleList = IMApplicationContext.getCircleDomainService().getGroupListMyGroupFirst(AccountHelper.getUidInt());

        Flowable<List<IMCircleEntityBook>> dbCircles = Flowable.create(new FlowableOnSubscribe<List<IMCircleEntityBook>>() {
            @Override
            public void subscribe(FlowableEmitter<List<IMCircleEntityBook>> emitter){
                try {
                    List<IMCircleEntityBook> dbCircleBook = new ArrayList<>();

                    for (IMUserEntity imUserEntity : circleList) {
                        IMCircleEntityBook imCircleEntityBook = new IMCircleEntityBook();
                        imCircleEntityBook.name = imUserEntity.getName();
                        imCircleEntityBook.groupLogo = imUserEntity.getAvatarPath();
                        imCircleEntityBook.grade = FormatUtil.parseInt(imUserEntity.getGroupLevel());
                        imCircleEntityBook.size = imUserEntity.getGroupCount();
                        imCircleEntityBook.joinState = true;
                        imCircleEntityBook.recommendCircle = false;
                        imCircleEntityBook.circleId = imUserEntity.getUserId();
                        imCircleEntityBook.identification = imUserEntity.isIdentification()?1:0;
                        imCircleEntityBook.bigClassId = imUserEntity.getCircleClass();
                        imCircleEntityBook.createById = imUserEntity.getCreateUserId();
                        dbCircleBook.add(imCircleEntityBook);
                    }
                    emitter.onNext(dbCircleBook);
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);

        mICircleEntries.clear();
        dbCircles
                .compose(RxUtil.<List<IMCircleEntityBook>>rxSchedulerHelper())
                .compose(((BaseActivity) mContext).<List<IMCircleEntityBook>>bindToLifecycle())
                .subscribe(new ResourceSubscriber<List<IMCircleEntityBook>>() {
                    @Override
                    public void onNext(List<IMCircleEntityBook> imCircleEntityBooks) {
                        if (imCircleEntityBooks.size()==0){
                            return;
                        }
                        mICircleEntries.addAll(imCircleEntityBooks);
                    }
                    @Override
                    public void onError(Throwable t) {
                        ProgressBarUtil.dismissProgress(mContext);
                        mCircleShareAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onComplete() {
                        ProgressBarUtil.dismissProgress(mContext);
                        mCircleShareAdapter.notifyDataSetChanged();
                    }
                });
    }
}
